#include "LayerParser.h"

#include "IdRefParser.h"
#include "LayerFunctionParser.h"
#include "SideParser.h"
#include "PolarityParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

LayerParser::LayerParser(
    QStringParser *&_nameParser
    , LayerFunctionParser *&_layerFunctionParser
    , SideParser *&_sideParser
    , PolarityParser *&_polarityParser
    , IdRefParser *&_specRefParser
):    m_nameParser(_nameParser)
    , m_layerFunctionParser(_layerFunctionParser)
    , m_sideParser(_sideParser)
    , m_polarityParser(_polarityParser)
    , m_specRefParser(_specRefParser)
{

}

bool LayerParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Layer());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("name")))
    {
        data = reader->attributes().value(QStringLiteral("name"));
        if (!m_nameParser->parse(reader, data))
            return false;
        m_result->name = m_nameParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("name: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("layerFunction")))
    {
        data = reader->attributes().value(QStringLiteral("layerFunction"));
        if (!m_layerFunctionParser->parse(reader, data))
            return false;
        m_result->layerFunction = m_layerFunctionParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("layerFunction: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("side")))
    {
        data = reader->attributes().value(QStringLiteral("side"));
        if (!m_sideParser->parse(reader, data))
            return false;
        m_result->side = m_sideParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("side: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("polarity")))
    {
        data = reader->attributes().value(QStringLiteral("polarity"));
        if (!m_polarityParser->parse(reader, data))
            return false;
        m_result->polarity = m_polarityParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("polarity: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("SpecRef"))
        {
            if (!m_specRefParser->parse(reader))
                return false;
            auto result = m_specRefParser->result();
            m_result->specRefList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Layer *LayerParser::result()
{
    return m_result.take();
}

}